package com;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.NestedIOException;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.google.common.collect.Maps.newHashMap;
import static java.util.concurrent.Executors.newScheduledThreadPool;

/**
 * Mybatis的mapper文件中的sql语句被修改后, 只能重启服务器才能被加载, 非常耗时,所以就写了一个自动加载的类,
 * 配置后检查xml文件更改,如果发生变化,重新加载xml里面的内容.
 *
 * 如果property smybatis.auto.mybatisAutoLoad存在,并且值不为false,创建bean.
 * @ConditionalOnProperty(prefix = "mybatis.auto",name = "mybatisAutoLoad" ,havingValue = "true")
 */
@Component
@ConditionalOnProperty(prefix = "mybatis.auto",value = "mybatisAutoLoad")
@ConfigurationProperties(prefix = "mybatis")
public class MapperLoader implements DisposableBean, InitializingBean, ApplicationContextAware {

    private ConfigurableApplicationContext context = null;
    private HashMap<String, String> fileMapping = newHashMap();
    private Scanner scanner = null;
    private ScheduledExecutorService service = null;

    @Getter
    @Setter
    private Auto auto;

    /**
     * 必须public static 否则无法加载配置文件
     */
    @Data
    public static class Auto{
        private String mybatisAutoLoad;
        private String basePath;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = (ConfigurableApplicationContext) applicationContext;

    }

    private void removeBean() {
        System.out.println("未配置mybatis.path,动态xml加载启用失败,尝试移除mapperLoader");
        BeanDefinitionRegistry beanDefinitionRegistry = (BeanDefinitionRegistry) context.getBeanFactory();
        if (beanDefinitionRegistry.containsBeanDefinition("mapperLoader")) {
            beanDefinitionRegistry.removeBeanDefinition("mapperLoader");
        }
        System.out.println("移除mapperLoader成功");

    }

    @Override
    public void afterPropertiesSet() {
        //是否开启xml动态加载
        try {
            if ("true".equals(auto.mybatisAutoLoad)) {
                //先尝试自动获取mybatis的xml文件路径配置
                try {
                    // 获取xml所在包
                    MapperScannerConfigurer config = context.getBean(MapperScannerConfigurer.class);

                    Field field = config.getClass().getDeclaredField("basePackage");
                    field.setAccessible(true);
                    auto.basePath = (String) field.get(config);
                } catch (NoSuchBeanDefinitionException e) {
                    //e.printStackTrace();
                    //未开启自动扫包,使用配置文件的根路径,xml文件目录
                    System.out.println("找不到MapperScannerConfigurer.class," +
                            "未启用扫包加载mapper,尝试使用配置目录mybatis.path");
                }
                //构建任务
                if (!StringUtils.isEmpty(auto.basePath)) {
                    System.out.println("开始构建动态加载xml任务");
                    service = newScheduledThreadPool(1);
                    // 触发文件监听事件
                    scanner = new Scanner();
                    scanner.scan();

                    service.scheduleAtFixedRate(new Task(), 5, 5, TimeUnit.SECONDS);
                    System.out.println("建动态加载xml任务构建成功");
                }
            }
        } catch (Exception e) {
           // e.printStackTrace();
            System.out.println("建动态加载xml任务失败");
        }finally {
            if (StringUtils.isEmpty(auto.basePath)) {
                //移除bean
                this.removeBean();
            }
        }
    }

    class Task implements Runnable {
        @Override
        public void run() {
            try {
                if (scanner.isChanged()) {
                    System.out.println("*Mapper.xml文件改变,重新加载.");
                    scanner.reloadXML();
                    System.out.println("加载完毕.");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @SuppressWarnings({"rawtypes"})
    class Scanner {

        private String[] basePackages;
        private static final String XML_RESOURCE_PATTERN = "**/*.xml";
        private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

        public Scanner() {
            basePackages = StringUtils.tokenizeToStringArray(MapperLoader.this.auto.basePath,
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
        }

        private Resource[] getResource(String basePackage, String pattern) throws IOException {
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                    + ClassUtils.convertClassNameToResourcePath(context.getEnvironment().resolveRequiredPlaceholders(
                    basePackage)) + "/" + pattern;
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            return resources;
        }

        private void reloadXML() throws Exception {
            SqlSessionFactory factory = context.getBean(SqlSessionFactory.class);
            Configuration configuration = factory.getConfiguration();
            // 移除加载项
            removeConfig(configuration);
            // 重新扫描加载
            for (String basePackage : basePackages) {
                Resource[] resources = getResource(basePackage, XML_RESOURCE_PATTERN);
                if (resources != null) {
                    for (int i = 0; i < resources.length; i++) {
                        if (resources[i] == null) {
                            continue;
                        }
                        try {
                            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resources[i].getInputStream(),
                                    configuration, resources[i].toString(), configuration.getSqlFragments());
                            xmlMapperBuilder.parse();
                        } catch (Exception e) {
                            throw new NestedIOException("Failed to parse mapping resource: '" + resources[i] + "'", e);
                        } finally {
                            ErrorContext.instance().reset();
                        }
                    }
                }
            }

        }

        private void removeConfig(Configuration configuration) throws Exception {
            Class<?> classConfig = configuration.getClass();
            clearMap(classConfig, configuration, "mappedStatements");
            clearMap(classConfig, configuration, "caches");
            clearMap(classConfig, configuration, "resultMaps");
            clearMap(classConfig, configuration, "parameterMaps");
            clearMap(classConfig, configuration, "keyGenerators");
            clearMap(classConfig, configuration, "sqlFragments");

            clearSet(classConfig, configuration, "loadedResources");

        }

        private void clearMap(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
            Field field = classConfig.getDeclaredField(fieldName);
            field.setAccessible(true);
            Map mapConfig = (Map) field.get(configuration);
            mapConfig.clear();
        }

        private void clearSet(Class<?> classConfig, Configuration configuration, String fieldName) throws Exception {
            Field field = classConfig.getDeclaredField(fieldName);
            field.setAccessible(true);
            Set setConfig = (Set) field.get(configuration);
            setConfig.clear();
        }

        private void scan() throws IOException {
            if (!fileMapping.isEmpty()) {
                return;
            }
            for (String basePackage : basePackages) {
                Resource[] resources = getResource(basePackage, XML_RESOURCE_PATTERN);
                if (resources != null) {
                    for (int i = 0; i < resources.length; i++) {
                        String multiKey = getValue(resources[i]);
                        fileMapping.put(resources[i].getFilename(), multiKey);
                    }
                }
            }
        }

        private String getValue(Resource resource) throws IOException {
            String contentLength = String.valueOf((resource.contentLength()));
            String lastModified = String.valueOf((resource.lastModified()));
            return new StringBuilder(contentLength).append(lastModified).toString();
        }

        public boolean isChanged() throws IOException {
            boolean isChanged = false;
            for (String basePackage : basePackages) {
                Resource[] resources = getResource(basePackage, XML_RESOURCE_PATTERN);
                if (resources != null) {
                    for (int i = 0; i < resources.length; i++) {
                        String name = resources[i].getFilename();
                        String value = fileMapping.get(name);
                        String multiKey = getValue(resources[i]);
                        if (!multiKey.equals(value)) {
                            isChanged = true;
                            fileMapping.put(name, multiKey);
                        }
                    }
                }
            }
            return isChanged;
        }
    }

    @Override
    public void destroy() {
        if (service != null) {
            service.shutdownNow();
        }
    }

}
